<?php

class csv_widget
{
    private $_CONTENT = '';
    private $_DATA = array();
    private $_file;
    private $_save_file_dir = '';
    private $_save_file = false;

    private function set_data() {
        $this->_CONTENT = join("\n", array_map(array(
            $this,
            'create_row_data'
        ), $this->_DATA));
    }

    private function exec_export() {
        $title = $this->_file;
        if ($this->_save_file) {
            file_put_contents($this->_save_file_dir . $title, $this->_CONTENT);
        } else {
            header("Content-type:text/csv");
            header("Content-Disposition:attachment;filename=" . $title . '.csv');
            header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
            header('Expires:0');
            header('Pragma:public');
            echo $this->_CONTENT;
            exit;
        }
    }

    private function create_row_data($row) {
        return join(',', array_map(array($this, 'format_column'), $row));
    }

    private function format_column($column) {

        if (preg_match('/[\x80-\xff]/', $column)) {
            $column = iconv('UTF-8', 'GBK//IGNORE', $column);
        }

        if (is_numeric($column)) {
            $column = '="' . $column . '"';
        } elseif (substr($column, 0, 1) === '"' || substr($column, 0, 1) === '=') {
            $column = '"' . str_replace('"', '""', $column) . '"';
        } elseif (is_string($column) && strpos($column, ',') > -1) {
            $column = '"' . $column . '"';
        }

        return $column;
    }

    public function export($file_name, $data, $save_file = false) {
        if (empty($data) || empty($file_name)) {
            return false;
        }

        $this->_file = $file_name;
        $this->_save_file = !!$save_file;

        $this->_DATA = $data;
        $this->set_data();

        $this->exec_export();
    }
}

?>